package com.lele.filter;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.FormContentFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CaptchaFilter extends FormContentFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 由于登录逻辑不是我去处理，那么我就拿不到验证码
        // 由于spring security是基于过滤器链的安全框架
        // 因此我们只需要在登录之前，添加一个过滤器，先来判断验证码是否正确
        // 用户请求的地址
        String uri = request.getRequestURI();

        if (uri.contains("/checkLogin")) {
            // 判断验证码
            // session中验证码
            String captcha = (String) request.getSession().getAttribute("captcha");
            // 用户输入验证码
            String formCaptcha = request.getParameter("captcha");
            // 用户没有输验证码
            if (StringUtils.isEmpty(formCaptcha)) {
                System.out.println("验证码不能为空");
                response.sendRedirect("userLogin");
                return;
            }
            // 验证码不正确
            if (!captcha.equalsIgnoreCase(formCaptcha)) {
                System.out.println("输入的验证码不正确");
                response.sendRedirect("userLogin");
                return;
            }
        }
        super.doFilterInternal(request, response, filterChain);
    }
}
